package com.ruoyi.develop.goodsSale.service.impl;

import com.ruoyi.common.core.domain.entity.SysArea;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.constants.BusinessConstants;
import com.ruoyi.develop.factory.factoryProduceSaleAll.domain.FactoryProduceSaleAll;
import com.ruoyi.develop.factory.factoryProduceSaleAll.service.IFactoryProduceSaleAllService;
import com.ruoyi.develop.goodsCustomer.domain.GoodsCustomer;
import com.ruoyi.develop.goodsOrderIn.domain.GoodsOrderIn;
import com.ruoyi.develop.goodsOrderIn.mapper.GoodsOrderInMapper;
import com.ruoyi.develop.goodsOrderInner.domain.GoodsOrderInner;
import com.ruoyi.develop.goodsOrderInner.service.IGoodsOrderInnerService;
import com.ruoyi.develop.goodsOrderMaterials.domain.GoodsOrderMaterials;
import com.ruoyi.develop.goodsOrderMaterials.service.IGoodsOrderMaterialsService;
import com.ruoyi.develop.goodsSale.domain.GoodsSale;
import com.ruoyi.develop.goodsSale.mapper.GoodsSaleMapper;
import com.ruoyi.develop.goodsSale.service.IGoodsSaleService;
import com.ruoyi.develop.goodsSaleMaterial.domain.GoodsSaleMaterial;
import com.ruoyi.develop.goodsSaleMaterial.service.IGoodsSaleMaterialService;
import com.ruoyi.develop.goodsSaledo.domain.GoodsSaledo;
import com.ruoyi.develop.goodsSaledo.service.IGoodsSaledoService;
import com.ruoyi.develop.goodsSaledoGongxu.domain.GoodsSaledoGongxu;
import com.ruoyi.develop.goodsSaledoGongxu.service.IGoodsSaledoGongxuService;
import com.ruoyi.develop.goodsScalaAll.domain.GoodsScalaAll;
import com.ruoyi.develop.goodsScalaAll.service.IGoodsScalaAllService;
import com.ruoyi.develop.lnGongyi.domain.LnGongyi;
import com.ruoyi.develop.lnGongyi.service.ILnGongyiService;
import com.ruoyi.develop.lnGongyigongxu.domain.LnGongyigongxu;
import com.ruoyi.develop.lnGongyigongxu.service.ILnGongyigongxuService;
import com.ruoyi.develop.lnGongyigoods.domain.LnGongyigoods;
import com.ruoyi.develop.lnGongyigoods.service.ILnGongyigoodsService;
import com.ruoyi.develop.lvRuku.domain.LvRuku;
import com.ruoyi.develop.lvRuku.service.ILvRukuService;
import com.ruoyi.develop.lvRukumingxi.domain.LvRukumingxi;
import com.ruoyi.develop.lvRukumingxi.service.ILvRukumingxiService;
import com.ruoyi.develop.lvYifahuomingxi.domain.LvYifahuomingxi;
import com.ruoyi.develop.lvYifahuomingxi.service.ILvYifahuomingxiService;
import com.ruoyi.develop.orderIronDetail.domain.OrderIronDetail;
import com.ruoyi.develop.orderIronRecord.domain.OrderIronRecord;
import com.ruoyi.develop.project.domain.Project;
import com.ruoyi.develop.projectBaseInfo.domain.ProjectBaseInfo;
import com.ruoyi.develop.projectBaseInfo.mapper.ProjectBaseInfoMapper;
import com.ruoyi.develop.projectBaseInfo.service.IProjectBaseInfoService;
import com.ruoyi.export.service.impl.ExportServiceImpl;
import com.ruoyi.framework.web.domain.server.Sys;
import com.ruoyi.system.service.ISysAreaService;
import org.apache.poi.ss.usermodel.DateUtil;
import org.jxls.reader.ReaderBuilder;
import org.jxls.reader.XLSReadStatus;
import org.jxls.reader.XLSReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.ruoyi.common.utils.PageUtils.startPage;

/**
 * 销售信息管理Service业务层处理
 *
 * @author qh
 * @date 2023-01-05
 */
@Service
public class GoodsSaleServiceImpl implements IGoodsSaleService {
    @Resource
    private GoodsSaleMapper goodsSaleMapper;
    @Resource
    private GoodsOrderInMapper goodsOrderInMapper;
    @Resource
    private IProjectBaseInfoService projectBaseInfoService;
    @Resource
    private IGoodsScalaAllService iGoodsScalaAllService;
    @Autowired
    private ISysAreaService areaService;
    @Autowired
    private ILnGongyiService lnGongyiService;
    @Autowired
    private IGoodsSaledoGongxuService iGoodsSaledoGongxuService;
    @Autowired
    private ILvRukuService lvRukuService;
    @Autowired
    private ILvRukumingxiService lvRukumingxiService;
    @Resource
    private ProjectBaseInfoMapper projectBaseInfoMapper;

    @Autowired
    private ExportServiceImpl exportService;
    @Autowired
    private ILnGongyigoodsService lnGongyigoodsService;
    @Autowired
    private ILnGongyigongxuService iLnGongyigongxuService;
    @Autowired
    private IGoodsOrderMaterialsService iGoodsOrderMaterialsService;
    @Autowired
    private IGoodsSaleMaterialService iGoodsSaleMaterialService;
    @Autowired
    private ILvYifahuomingxiService yifahuomingxiService;
    @Autowired
    private IGoodsSaledoService saledoService;
    @Autowired
    private IFactoryProduceSaleAllService factoryProduceSaleAllService;
    @Autowired
    private ILnGongyiService iLnGongyiService;
    @Autowired
    private IGoodsOrderInnerService goodsOrderInnerService;
    @Value(value = "${ruoyi.path}")
    public String basePath;
    @Value(value = "${ruoyi.templatePath}")
    public String templatePath;
    @Value(value = "${ruoyi.templateImport}")
    public String templateImport;

    /**
     * 查询销售信息管理
     *
     * @param id 销售信息管理主键
     * @return 销售信息管理
     */
    @Override
    public GoodsSale selectById(String id) {
        return goodsSaleMapper.selectById(id);
    }

    /**
     * 查询销售信息管理列表
     *
     * @param entity 销售信息管理
     * @return 销售信息管理
     */
    @Override
    public List<GoodsSale> selectList(GoodsSale entity) {
        return goodsSaleMapper.selectList(entity);
    }

    @Override
    public List<GoodsSale> listAndFour(GoodsSale entity) {
        return goodsSaleMapper.listAndFour(entity);
    }
    @Override
    public List<GoodsSale> listProject(GoodsSale entity) {
        return goodsSaleMapper.listProject(entity);
    }
    @Override
    public List<GoodsSale> listFinishDo(GoodsSale entity) {
        return goodsSaleMapper.listFinishDo(entity);
    }
    @Override
    public List<GoodsSale> selectListNotZero(GoodsSale entity) {
        return goodsSaleMapper.selectListNotZero(entity);
    }

    @Override
    public List<GoodsSale> listSendNotZero(GoodsSale entity) {
        return goodsSaleMapper.listSendNotZero(entity);
    }


    @Override
    public List<GoodsSale> listNoQishen(GoodsSale entity) {
        return goodsSaleMapper.listNoQishen(entity);
    }

    @Override
    public List<GoodsSale> listByProjectId(GoodsSale entity) {
        return goodsSaleMapper.listByProjectId(entity);
    }
    @Override
    public List<GoodsSale> selectListNotProject(GoodsSale entity) {
        return goodsSaleMapper.selectListNotProject(entity);
    }
    @Override
    public List<GoodsSale> selectByProjectId(String projectId) {
        return goodsSaleMapper.selectByProjectId(projectId);
    }
    @Override
    public List<GoodsSale> listBatch(String[] ids) {
        return goodsSaleMapper.listBatch(ids);
    }

    @Override
    public List<GoodsSale> listByProAndOrder(GoodsSale entity) {
        return goodsSaleMapper.listByProAndOrder(entity);
    }

    /**
     * 新增销售信息管理
     *
     * @param entity 销售信息管理
     * @return 结果
     */
    @Override
    public int insert(GoodsSale entity) {
        if (StringUtils.isBlank(entity.getId())) {
            entity.setId(IdUtils.fastSimpleUUID());
        }
        entity.setCreateBy(SecurityUtils.getUsername());
        entity.setCreateTime(DateUtils.getNowDate());
        entity.setFahuoShengyu(entity.getOrderCount());
        return goodsSaleMapper.insert(entity);
    }

    //非订单自制产品新增
    @Override
    public int addNotProject(GoodsSale entity) {
        if (StringUtils.isBlank(entity.getId())) {
            entity.setId(IdUtils.fastSimpleUUID());
        }
        entity.setCreateBy(SecurityUtils.getUsername());
        entity.setCreateTime(DateUtils.getNowDate());
        entity.setFahuoShengyu(entity.getOrderCount());
        entity.setPleaseBuyCount(entity.getOrderCount());
        entity.setStatus(BusinessConstants.SALE_TYPE_5);//待自制
        goodsSaleMapper.insert(entity);

        GoodsSale goodsSale2 = goodsSaleMapper.selectById(entity.getId());
        if ( goodsSale2 != null) {
            if(StringUtils.isNotBlank(goodsSale2.getGongyiId())) {
                LnGongyi lnGongyi=iLnGongyiService.selectById(goodsSale2.getGongyiId());
                if(lnGongyi!=null) {
                    goodsSale2.setGongyiId(goodsSale2.getGongyiId());
                    goodsSale2.setGongyiName(lnGongyi.getName());
                    goodsSale2.setGongyiCode(lnGongyi.getCode());
                    goodsSale2.setGongyiFile(lnGongyi.getFile());
                    goodsSale2.setGongyiPhoto(lnGongyi.getPhoto());
                    goodsSale2.setGongyiShuoming(lnGongyi.getShuoming());
                    goodsSale2.setState(BusinessConstants.SALE_STATE_1);//已分配任务
                    goodsSaleMapper.update(goodsSale2);
                }
            }
        }

        iGoodsSaledoGongxuService.deleteBySaleId(entity.getId());

        List<LnGongyigoods> lnGongyigongxuList=lnGongyigoodsService.selectByGoods(entity.getGoodsId());
        if(lnGongyigongxuList.size()>=1){
            List<LnGongyigongxu> lnGongyigongxus=iLnGongyigongxuService.selectByGongyi(lnGongyigongxuList.get(0).getGongyiId());
            if(lnGongyigongxus!=null){
                goodsSale2.setState(BusinessConstants.GONGXU_STATUS_1);//已分配任务
                goodsSaleMapper.update(goodsSale2);
                for (LnGongyigongxu entity1 : lnGongyigongxus) {
                    GoodsSaledoGongxu goodsSaledoGongxu = new GoodsSaledoGongxu();
                    goodsSaledoGongxu.setSaleId(goodsSale2.getId());
                    goodsSaledoGongxu.setGoodsId(goodsSale2.getGoodsId());
                    goodsSaledoGongxu.setGongyiId(goodsSale2.getGongyiId());
                    goodsSaledoGongxu.setGongyiName(goodsSale2.getGongyiName());
                    goodsSaledoGongxu.setGongyiCode(goodsSale2.getGongyiCode());
                    goodsSaledoGongxu.setGongxuId(entity.getId());
                    goodsSaledoGongxu.setCode(entity1.getCode());
                    goodsSaledoGongxu.setName(entity1.getName());
                    goodsSaledoGongxu.setPhoto(entity1.getPhoto());
                    goodsSaledoGongxu.setFile(entity1.getFile());
                    goodsSaledoGongxu.setShuoming(entity1.getShuoming());
                    goodsSaledoGongxu.setMoney(entity1.getMoney());
                    goodsSaledoGongxu.setCounts(goodsSale2.getPleaseBuyCount());
                    goodsSaledoGongxu.setFenpeiCount(BigDecimal.ZERO);
                    goodsSaledoGongxu.setRemainCount(goodsSale2.getPleaseBuyCount());
                    goodsSaledoGongxu.setFinishCount(BigDecimal.ZERO);
                    goodsSaledoGongxu.setRemainfinishCount(goodsSale2.getPleaseBuyCount());
                    iGoodsSaledoGongxuService.insert(goodsSaledoGongxu);
                }
            }
        }
        List<GoodsOrderMaterials> goodsOrderMaterialsList = iGoodsOrderMaterialsService.selectByGoodsId(entity.getGoodsId());
        if(goodsOrderMaterialsList.size() > 0){
            goodsSale2.setIschaijie(BusinessConstants.TYPE_CHAIJIE_YES);//已拆解
            goodsSaleMapper.update(goodsSale2);
            for(GoodsOrderMaterials goodsOrderMaterials:goodsOrderMaterialsList){
                GoodsSaleMaterial goodsSaleMaterial=new GoodsSaleMaterial();
                BeanUtils.copyProperties(goodsOrderMaterials, goodsSaleMaterial, "id");
                goodsSaleMaterial.setGsaleId(entity.getId());
                goodsSaleMaterial.setGoodsId(goodsOrderMaterials.getMaterialId());
                //goodsSaleMaterial.setSupplierId(goodsSaledo.getSupplierId());
                goodsSaleMaterial.setSupplierName("库存");
                //goodsSaleMaterial.setSaleName(goodsSaledo.getSalesmanName());
                //goodsSaleMaterial.setProjectId(goodsSaledo.getProjectId());
                //goodsSaleMaterial.setProjectName(goodsSaledo.getProjectName());
                //goodsSaleMaterial.setProjectNo(goodsSaledo.getProjectNo());
                goodsSaleMaterial.setGoodsCount(entity.getOrderCount());
                goodsSaleMaterial.setShengyuCount(entity.getOrderCount());
                goodsSaleMaterial.setGoodsBuyTotal(entity.getOrderCount().multiply(goodsOrderMaterials.getGoodsBuyPrice()));

                iGoodsSaleMaterialService.insert(goodsSaleMaterial);
            }
        }
        return 1;
    }
    @Override
    @Transactional
    public void insertBatch(GoodsSale goodsSale) {
        BigDecimal counts = goodsSale.getOrderCount();
        List<GoodsOrderIn> rows = goodsSale.getColumns();
        ProjectBaseInfo projectBaseInfo = projectBaseInfoService.selectById(goodsSale.getProjectId());
        BigDecimal saleMoney = BigDecimal.ZERO;//订单总价
        BigDecimal feeMoney = BigDecimal.ZERO;//费用
        BigDecimal buyMoney = BigDecimal.ZERO;//成本价
        if (!rows.isEmpty()) {
            for (GoodsOrderIn entity : rows) {
                goodsSale = goodsSaleMapper.selectByCodeAndProjectAndStatus(entity.getCode(), goodsSale.getProjectId(), BusinessConstants.SALE_TYPE_0);
                if (goodsSale != null) {
                    goodsSale.setGoodsType(entity.getType());
                    //销售单价（订单单价）
                    goodsSale.setGoodsUnitPrice(entity.getGoodsUnitPrice());
                    //销售数量
                    goodsSale.setGoodsCount(entity.getGoodsCount().add(goodsSale.getGoodsCount()));
                    //剩余数量
                    if (goodsSale.getOrderCount().compareTo(BigDecimal.ZERO) > 0) {
                        goodsSale.setPleaseBuyCount(goodsSale.getOrderCount().subtract(goodsSale.getGoodsCount()));
                    }
                    //销售总价（订单总价）
                    goodsSale.setGoodsTotalPrice(goodsSale.getGoodsUnitPrice().multiply(goodsSale.getGoodsCount()));
                    //成本价格
                    goodsSale.setGoodsBuyTotal(entity.getCostPrice().multiply(entity.getGoodsCount()).add(goodsSale.getGoodsBuyTotal()));
                    //利润
                    goodsSale.setGoodsProfit(goodsSale.getGoodsTotalPrice().subtract(goodsSale.getGoodsBuyTotal()));
                    update(goodsSale);
                } else {
                    goodsSale = new GoodsSale();
                    goodsSale.setId(IdUtils.fastSimpleUUID());
                    goodsSale.setProjectId(projectBaseInfo.getId());
                    goodsSale.setProjectName(projectBaseInfo.getName());
                    goodsSale.setProjectNo(projectBaseInfo.getCode());
                    goodsSale.setType("2");
                    goodsSale.setGoodsCode(entity.getCode());
                    goodsSale.setGoodsUnitPrice(entity.getGoodsUnitPrice());
                    goodsSale.setGoodsId(entity.getId());
                    goodsSale.setGoodsName(entity.getName());
                    goodsSale.setGoodsType(entity.getType());
                    goodsSale.setGoodsBrand(entity.getBrand());
                    goodsSale.setGoodModel(entity.getModel());
                    goodsSale.setSupplierId(entity.getSupplierId());
                    goodsSale.setSupplierName(entity.getSupplierName());
                    goodsSale.setGoodsCount(entity.getGoodsCount());
                    goodsSale.setGoodsTotalPrice(entity.getGoodsTotalPrice());
                    //购入成本
                    goodsSale.setGoodsBuyPrice(entity.getCostPrice());
                    goodsSale.setGoodsBuyTotal(entity.getCostPrice().multiply(entity.getGoodsCount()));
                    //销售盈利
                    goodsSale.setGoodsProfit(goodsSale.getGoodsTotalPrice().subtract(goodsSale.getGoodsBuyTotal()));
                    if (goodsSale.getSaleDate() == null) {
                        goodsSale.setSaleDate(entity.getBuyDate());
                    }
                    if (goodsSale.getSaleId() == null) {
                        goodsSale.setSaleId(SecurityUtils.getUserId());
                    }
                    if (goodsSale.getSaleName() == null) {
                        goodsSale.setSaleName(SecurityUtils.getNickName());
                    }
                    goodsSale.setOrderCount(counts);
                    //goodsSale.setCounts(BigDecimal.valueOf(10));
                    System.out.println(counts + "    " + goodsSale.getOrderCount());
                    if (entity.getGoodsCount().compareTo(BigDecimal.ZERO) > 0) {
                        goodsSale.setPleaseBuyCount(goodsSale.getOrderCount().subtract(entity.getGoodsCount()));
                    }
                    insert(goodsSale);
                }

                GoodsScalaAll goodsSaleAll = new GoodsScalaAll();
                goodsSaleAll.setId(IdUtils.fastSimpleUUID());
                goodsSaleAll.setProjectId(projectBaseInfo.getId());
                goodsSaleAll.setProjectName(projectBaseInfo.getName());
                goodsSale.setType("2");
                goodsSale.setGoodsCode(entity.getCode());
                goodsSaleAll.setGoodsId(entity.getId());
                goodsSaleAll.setGoodsName(entity.getName());
                goodsSaleAll.setGoodsBrand(entity.getBrand());
                goodsSaleAll.setGoodModel(entity.getModel());
                goodsSaleAll.setSupplierId(entity.getSupplierId());
                goodsSaleAll.setSupplierName(entity.getSupplierName());

                goodsSaleAll.setGoodsUnitPrice(entity.getGoodsUnitPrice());
                goodsSaleAll.setGoodsCount(entity.getGoodsCount());
                goodsSaleAll.setGoodsTotalPrice(entity.getGoodsTotalPrice());
                //购入成本
                goodsSaleAll.setGoodsBuyPrice(entity.getCostPrice());
                goodsSaleAll.setGoodsBuyTotal(entity.getCostPrice().multiply(entity.getGoodsCount()));
                //销售盈利
                goodsSaleAll.setGoodsProfit(goodsSaleAll.getGoodsTotalPrice().subtract(goodsSaleAll.getGoodsBuyTotal()));
                if (goodsSaleAll.getSaleDate() == null) {
                    goodsSaleAll.setSaleDate(entity.getBuyDate());
                }
                if (goodsSaleAll.getSaleId() == null) {
                    goodsSaleAll.setSaleId(SecurityUtils.getUserId());
                }
                if (goodsSaleAll.getSaleName() == null) {
                    goodsSaleAll.setSaleName(SecurityUtils.getNickName());
                }
                if (projectBaseInfo != null && StringUtils.isNotBlank(projectBaseInfo.getName())) {
                    goodsSaleAll.setCustomerId(projectBaseInfo.getCustomId());
                    goodsSaleAll.setCustomerName(projectBaseInfo.getCustomName());
                    //处理项目研发经费,销售信息
                    if (BusinessConstants.TYPE_PROJECT.equals(goodsSaleAll.getType())) {
                        saleMoney = saleMoney.add(goodsSaleAll.getGoodsTotalPrice());//总价（订单总价）销售总价
                        buyMoney = buyMoney.add(goodsSaleAll.getGoodsBuyTotal());//成本金额（总成本价）
                    } else if (BusinessConstants.TYPE_PROJECT_FEE.equals(goodsSaleAll.getType())) {//3为项目费用
                        feeMoney = feeMoney.add(goodsSaleAll.getGoodsTotalPrice());
                    }
                }
                goodsSaleAll.setMainId(goodsSale.getId());
                iGoodsScalaAllService.insert(goodsSaleAll);


                entity.setRemainderCount(entity.getRemainderCount().subtract(entity.getGoodsCount()));
                entity.setShengyu(entity.getRemainderCount().multiply(entity.getCostPrice()));
                entity.setBuyDate(null);
                goodsOrderInMapper.update(entity);
                SysArea sysArea = areaService.selectAreaById(entity.getDeptId());
                if (sysArea != null) {
                    sysArea.setShengyu(sysArea.getShengyu().subtract(entity.getRemainderCount()));
                    sysArea.setAllmaoney(sysArea.getAllmaoney().subtract(entity.getShengyu()));
                    areaService.updateArea(sysArea);
                }
            }
        }
        if (projectBaseInfo != null && StringUtils.isNotBlank(projectBaseInfo.getName())) {
            projectBaseInfo.setSaleMoney(projectBaseInfo.getSaleMoney().add(saleMoney));//总价（订单总价）销售总价
            projectBaseInfo.setBuyMoney(projectBaseInfo.getBuyMoney().add(buyMoney));//成本金额（总成本价）
            projectBaseInfo.setFeeMoney(projectBaseInfo.getFeeMoney().add(feeMoney));//项目费用
            projectBaseInfoService.update(projectBaseInfo);
        }
    }

    @Override
    @Transactional
    public void insertForPrjNew(GoodsSale goodsSale) {
        List<GoodsOrderIn> rows = goodsSale.getColumns();
        ProjectBaseInfo projectBaseInfo = projectBaseInfoService.selectById(goodsSale.getProjectId());

        if (!rows.isEmpty()) {
            for (GoodsOrderIn entity : rows) {
                goodsSale = new GoodsSale();
                if(StringUtils.isNotBlank(entity.getInnerGoodsId())){
                    GoodsOrderInner goodsOrderInner = goodsOrderInnerService.selectById(entity.getInnerGoodsId());
                    goodsSale.setInnerGoodsId(goodsOrderInner.getId());
                    goodsSale.setInnerGoodsCode(goodsOrderInner.getCode());
                    goodsSale.setInnerGoodsName(goodsOrderInner.getName());
                }
                goodsSale.setId(IdUtils.fastSimpleUUID());
                goodsSale.setProjectId(projectBaseInfo.getId());
                goodsSale.setProjectName(projectBaseInfo.getName());
                goodsSale.setProjectNo(projectBaseInfo.getCode());
                goodsSale.setType("2");
                goodsSale.setContractGoodsName(entity.getContractGoodsName());
                goodsSale.setDeliveryTime(entity.getDeliveryTime());
                goodsSale.setRemark(entity.getRemark());
                goodsSale.setGoodsCode(entity.getCode());
                goodsSale.setGoodsId(entity.getId());
                goodsSale.setGoodsName(entity.getName());
                goodsSale.setGoodsType(entity.getType());
                goodsSale.setGoodsBrand(entity.getBrand());
                goodsSale.setGoodModel(entity.getModel());
                goodsSale.setSupplierId(entity.getSupplierId());
                goodsSale.setSupplierName(entity.getSupplierName());
                goodsSale.setGongchengName(entity.getGongchengName());
                goodsSale.setProjectDept(entity.getProjectDept());
                goodsSale.setGoodsTaxUnitPrice(entity.getGoodsTaxUnitPrice());
                goodsSale.setGoodsTaxTotalPrice(entity.getGoodsTaxTotalPrice());
                goodsSale.setRemark(entity.getRemark());
                goodsSale.setDeliveryPerson(entity.getDeliveryPerson());
                if (entity.getGoodsUnitPrice() != null) {
                    goodsSale.setGoodsUnitPrice(entity.getGoodsUnitPrice());
                }
                if (entity.getCounts() != null) {
                    goodsSale.setOrderCount(entity.getCounts());
                }
                if (entity.getGoodsTotalPrice() != null) {
                    goodsSale.setGoodsTotalPrice(entity.getGoodsTotalPrice());
                }
                //goodsSale.setGoodsBuyTotal(entity.getCostPriceTax().multiply(entity.getGoodsCount()));
                if (goodsSale.getSaleDate() == null) {
                    goodsSale.setSaleDate(entity.getBuyDate());
                }
                if (goodsSale.getSaleId() == null) {
                    goodsSale.setSaleId(SecurityUtils.getUserId());
                }
                if (goodsSale.getSaleName() == null) {
                    goodsSale.setSaleName(SecurityUtils.getNickName());
                }
                if (projectBaseInfo != null && StringUtils.isNotBlank(projectBaseInfo.getName())) {
                    goodsSale.setCustomerId(projectBaseInfo.getCustomId());
                    goodsSale.setCustomerName(projectBaseInfo.getCustomName());
                }
                insert(goodsSale);
            }
        }
        calculateOrderContractMoney(projectBaseInfo);
    }

    public void calculateOrderContractMoney(ProjectBaseInfo order){
        GoodsSale goodsSale  = new GoodsSale();
        goodsSale.setProjectId(order.getId());
        List<GoodsSale> goodsSaleList = goodsSaleMapper.selectList(goodsSale);
        // 销售总价
        BigDecimal contractMoney = new BigDecimal(0);
        for(GoodsSale sale : goodsSaleList){
            contractMoney = contractMoney.add(sale.getGoodsTaxTotalPrice());
        }
        order.setContractMoney(contractMoney);
        projectBaseInfoService.update(order);
    }


    @Override
    @Transactional
    public void insertRuku(GoodsSale goodsSale) {
        ProjectBaseInfo projectBaseInfo = projectBaseInfoMapper.selectById(goodsSale.getProjectId());
        List<GoodsSale> rows = goodsSale.getColumnsGoodsSale();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String today = sdf.format(new Date());
        String codeMaxString = lvRukuService.selectMaxCode(today);
        if(StringUtils.isNotBlank(codeMaxString)){
            // 最大编号+1
            codeMaxString = Long.parseLong(codeMaxString)+1+"";
        }else{
            codeMaxString = today+"0001";
        }
        LvRuku lvRuku = new LvRuku();
        lvRuku.setNos(codeMaxString);
        lvRuku.setState(BusinessConstants.GOODS_8);
        lvRuku.setRukuDate(new Date());
        lvRuku.setRukuid(SecurityUtils.getLoginUser().getUserId());
        lvRuku.setRukupeople(SecurityUtils.getLoginUser().getUsername());
        lvRuku.setType(BusinessConstants.GOODS_TYPE_HARDWARE);
        lvRuku.setYwType(BusinessConstants.TYPE_RUKU);
        lvRuku.setMainId(goodsSale.getProjectId());
        lvRuku.setName(projectBaseInfo.getName());
        lvRuku.setCode(projectBaseInfo.getCode());
        lvRukuService.insert(lvRuku);
        if (!rows.isEmpty()) {
            for (GoodsSale entity : rows) {
                GoodsSale goodsSale1 = goodsSaleMapper.selectById(entity.getId());
                goodsSale1.setStatus(BusinessConstants.GOODS_8);//待入库
                goodsSale1.setRukuCount(goodsSale1.getRukuCount().add(entity.getPleaseBuyCount()));
                goodsSale1.setWeiruCount(goodsSale1.getPleaseBuyCount().subtract(goodsSale1.getRukuCount()));
                goodsSaleMapper.update(goodsSale1);

                String codeMaxStringMingxi = lvRukumingxiService.selectMaxCode(today);
                if(StringUtils.isNotBlank(codeMaxString)){
                    // 最大编号+1
                    codeMaxStringMingxi = Long.parseLong(codeMaxString)+1+"";
                }else{
                    codeMaxStringMingxi = today+"0001";
                }
                LvRukumingxi lvRukumingxi = new LvRukumingxi();
                lvRukumingxi.setParentId(lvRuku.getId());//入库单id
                lvRukumingxi.setIsdo(BusinessConstants.STATUS_YES);//自制
                lvRukumingxi.setUnit(goodsSale1.getUnit());
                lvRukumingxi.setRemark(goodsSale1.getRemark());
                lvRukumingxi.setGoodsSaleId(goodsSale1.getId());
                lvRukumingxi.setGoodsId(goodsSale1.getGoodsId());
                lvRukumingxi.setCode(goodsSale1.getGoodsCode());
                lvRukumingxi.setNos(codeMaxStringMingxi);
                lvRukumingxi.setStatus(BusinessConstants.STORAGE_STATE_UN);
                lvRukumingxi.setRukudate(new Date());
                lvRukumingxi.setRukuno(codeMaxString);//入库编号
                lvRukumingxi.setIsZhijian(BusinessConstants.STATUS_YES);//
                lvRukumingxi.setRukuren(SecurityUtils.getLoginUser().getUsername());
                lvRukumingxi.setCustomerId(projectBaseInfo.getCustomId());
                lvRukumingxi.setCustomerName(projectBaseInfo.getCustomName());
                lvRukumingxi.setSaleId(projectBaseInfo.getSaleId());
                lvRukumingxi.setSaleName(projectBaseInfo.getSalesmanName());
                lvRukumingxi.setGoodsTotalPrice(projectBaseInfo.getSaleMoney());
                lvRukumingxi.setProjectId(projectBaseInfo.getId());
                lvRukumingxi.setProjectName(projectBaseInfo.getName());
                lvRukumingxi.setProjectNo(projectBaseInfo.getCode());
                lvRukumingxi.setGoodsType(BusinessConstants.GOODS_TYPE_HARDWARE);//产品类型
                lvRukumingxi.setType(BusinessConstants.TYPE_RUKU);//产品出入库类型
                lvRukumingxi.setDaohuoCount(entity.getPleaseBuyCount());//出入库数量
                lvRukumingxi.setCanCount(entity.getPleaseBuyCount());
                lvRukumingxiService.insert(lvRukumingxi);
            }
        }
    }

    //自制产品提交到质检
    @Override
    @Transactional
    public void insertRukuToZhijian(GoodsSale goodsSale) {
        List<GoodsSale> rows = goodsSale.getColumnsGoodsSale();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String today = sdf.format(new Date());
        String codeMaxString = lvRukuService.selectMaxCode(today);
        if(StringUtils.isNotBlank(codeMaxString)){
            // 最大编号+1
            codeMaxString = Long.parseLong(codeMaxString)+1+"";
        }else{
            codeMaxString = today+"0001";
        }
        /*LvRuku lvRuku = new LvRuku();
        lvRuku.setNos(codeMaxString);
        lvRuku.setState(BusinessConstants.GOODS_8);
        lvRuku.setRukuDate(new Date());
        lvRuku.setRukuid(SecurityUtils.getLoginUser().getUserId());
        lvRuku.setRukupeople(SecurityUtils.getLoginUser().getUsername());
        lvRuku.setType(BusinessConstants.GOODS_TYPE_HARDWARE);
        lvRuku.setYwType(BusinessConstants.TYPE_RUKU);
        lvRuku.setMainId(goodsSale.getProjectId());
        lvRuku.setName(rows.get(0).getGongchengName());
        lvRuku.setCode(rows.get(0).getProjectNo());
        lvRukuService.insert(lvRuku);*/
        if (!rows.isEmpty()) {
            for (GoodsSale entity : rows) {
                GoodsSale goodsSale1 = goodsSaleMapper.selectById(entity.getId());
                goodsSale1.setStatus(BusinessConstants.SALE_TYPE_7);//已收货
                //goodsSale1.setRukuCount(goodsSale1.getRukuCount().add(entity.getPleaseBuyCount()));
                //goodsSale1.setWeiruCount(goodsSale1.getPleaseBuyCount().subtract(goodsSale1.getRukuCount()));
                goodsSale1.setKerukuCount(goodsSale1.getKerukuCount().subtract(entity.getKerukuCount()));
                goodsSale1.setDaizhijianCount(goodsSale1.getDaizhijianCount().add(entity.getKerukuCount()));
                goodsSaleMapper.update(goodsSale1);
                ProjectBaseInfo projectBaseInfo=new ProjectBaseInfo();
                if(goodsSale1.getProjectId()!=null){
                    projectBaseInfo=projectBaseInfoService.selectById(goodsSale1.getProjectId());
                }

                String codeMaxStringMingxi = lvRukumingxiService.selectMaxCode(today);
                if(StringUtils.isNotBlank(codeMaxString)){
                    // 最大编号+1
                    codeMaxStringMingxi = Long.parseLong(codeMaxString)+1+"";
                }else{
                    codeMaxStringMingxi = today+"0001";
                }
                LvRukumingxi lvRukumingxi = new LvRukumingxi();
                //lvRukumingxi.setParentId(lvRuku.getId());//入库单id
                lvRukumingxi.setIsdo(BusinessConstants.STATUS_YES);//自制
                lvRukumingxi.setUnit(goodsSale1.getUnit());
                lvRukumingxi.setRemark(goodsSale1.getRemark());
                lvRukumingxi.setGoodsSaleId(goodsSale1.getId());
                lvRukumingxi.setGoodsId(goodsSale1.getGoodsId());
                lvRukumingxi.setCode(goodsSale1.getGoodsCode());
                lvRukumingxi.setNos(codeMaxStringMingxi);
                lvRukumingxi.setStatus(BusinessConstants.STORAGE_STATE_UN);
                lvRukumingxi.setRukudate(new Date());
                lvRukumingxi.setRukuno(codeMaxString);//入库编号
                lvRukumingxi.setIsZhijian(BusinessConstants.INSPECT_STATE_UN);//
                lvRukumingxi.setRukuren(SecurityUtils.getLoginUser().getUsername());
                if(projectBaseInfo!=null){
                    lvRukumingxi.setCustomerId(projectBaseInfo.getCustomId());
                    lvRukumingxi.setCustomerName(projectBaseInfo.getCustomName());
                    lvRukumingxi.setSaleId(projectBaseInfo.getSaleId());
                    lvRukumingxi.setSaleName(projectBaseInfo.getSalesmanName());
                    lvRukumingxi.setGoodsTotalPrice(projectBaseInfo.getSaleMoney());
                }
                lvRukumingxi.setProjectId(goodsSale1.getProjectId());
                lvRukumingxi.setProjectName(goodsSale1.getGongchengName());
                lvRukumingxi.setProjectNo(goodsSale1.getProjectNo());
                lvRukumingxi.setGoodsType(BusinessConstants.GOODS_TYPE_HARDWARE);//产品类型
                lvRukumingxi.setType(BusinessConstants.TYPE_RUKU);//产品出入库类型

                lvRukumingxi.setDaohuoCount(entity.getKerukuCount());//出入库数量
                lvRukumingxi.setCanCount(entity.getKerukuCount());
                lvRukumingxi.setProductdate(entity.getProductdate());

   /*             lvRukumingxi.setDaohuoCount(entity.getPleaseBuyCount());//出入库数量
                lvRukumingxi.setCanCount(entity.getPleaseBuyCount());
                lvRukumingxi.setDaohuoCount(entity.getYurukuCount());//出入库数量
                lvRukumingxi.setCanCount(entity.getYurukuCount());*/

                lvRukumingxi.setDoremark(entity.getDoremark());
                lvRukumingxi.setDouser(entity.getDouser());
                //lvRukumingxi.setGoodsBuyPrice(lvYifahuomingxi.getDanjian());//发货成本单件
                //lvRukumingxi.setGoodsBuyTotal(lvYifahuomingxi.getMoney());//发货成本总价
                //lvRukumingxi.setGoodsProfit(goodsSale.getGoodsTotalPrice().subtract(lvYifahuomingxi.getMoney()));//利润=销售价-成本
                /*if(BusinessConstants.GOODS_TYPE_MATERIAL.equals(lvYifahuomingxi.getGoodsType())) {
                    lvRukumingxi.setDun(goodsSale.getCount());//到货吨位
                }*/
                lvRukumingxiService.insert(lvRukumingxi);
            }
        }
    }

    @Override
    @Transactional
    public void insertForPrjGygx(GoodsSale goodsSale) {
        List<GoodsSaledoGongxu> rows = goodsSale.getColumnsGongxu();
        LnGongyi lnGongyi = lnGongyiService.selectById(goodsSale.getGongyiId());
        FactoryProduceSaleAll factoryProduceSaleAll = factoryProduceSaleAllService.selectById(goodsSale.getSaleId());
        if (lnGongyi != null && factoryProduceSaleAll != null) {
            factoryProduceSaleAll.setGongyiId(goodsSale.getGongyiId());
            factoryProduceSaleAll.setGongyiName(lnGongyi.getName());
            factoryProduceSaleAll.setGongyiCode(lnGongyi.getCode());
            factoryProduceSaleAll.setGongyiFile(lnGongyi.getFile());
            factoryProduceSaleAll.setGongyiPhoto(lnGongyi.getPhoto());
            factoryProduceSaleAll.setGongyiShuoming(lnGongyi.getShuoming());
            factoryProduceSaleAll.setStatus(BusinessConstants.PROD_STATUS_2);//已分配工艺工序
            factoryProduceSaleAll.setIssheding(BusinessConstants.PROD_STATUS_2);//已分配工艺工序
            factoryProduceSaleAllService.update(factoryProduceSaleAll);
        }
        iGoodsSaledoGongxuService.deleteBySaleId(goodsSale.getSaleId());
        if (!rows.isEmpty()) {
            for (GoodsSaledoGongxu entity : rows) {
                GoodsSaledoGongxu goodsSaledoGongxu = new GoodsSaledoGongxu();
                goodsSaledoGongxu.setSaleId(factoryProduceSaleAll.getId());
                goodsSaledoGongxu.setGoodsId(factoryProduceSaleAll.getGoodsId());
                goodsSaledoGongxu.setGongyiId(factoryProduceSaleAll.getGongyiId());
                goodsSaledoGongxu.setGongyiName(factoryProduceSaleAll.getGongyiName());
                goodsSaledoGongxu.setGongyiCode(factoryProduceSaleAll.getGongyiCode());
                goodsSaledoGongxu.setGongxuId(entity.getId());
                goodsSaledoGongxu.setCode(entity.getCode());
                goodsSaledoGongxu.setName(entity.getName());
                goodsSaledoGongxu.setGongxuName(entity.getGoodsName());
                goodsSaledoGongxu.setGongxuModel(entity.getGoodsModel());
                goodsSaledoGongxu.setPhoto(entity.getPhoto());
                goodsSaledoGongxu.setFile(entity.getFile());
                goodsSaledoGongxu.setShuoming(entity.getShuoming());
                goodsSaledoGongxu.setMoney(entity.getMoney());
                goodsSaledoGongxu.setCounts(factoryProduceSaleAll.getCount());
                goodsSaledoGongxu.setFenpeiCount(BigDecimal.ZERO);
                goodsSaledoGongxu.setRemainCount(factoryProduceSaleAll.getCount());
                goodsSaledoGongxu.setFinishCount(BigDecimal.ZERO);
                goodsSaledoGongxu.setRemainfinishCount(factoryProduceSaleAll.getCount());
                goodsSaledoGongxu.setDeptId(entity.getDeptId());
                goodsSaledoGongxu.setDeptName(entity.getDeptName());
                goodsSaledoGongxu.setWorkHour(entity.getWorkHour());
                iGoodsSaledoGongxuService.insert(goodsSaledoGongxu);
            }
        }
    }

    @Override
    @Transactional
    public void insertForPrjGygxAll(GoodsSale goodsSale) {
        List<GoodsSaledoGongxu> rows = goodsSale.getColumnsGongxu();
        LnGongyi lnGongyi = lnGongyiService.selectById(goodsSale.getGongyiId());
        for (int i = 0; i < goodsSale.getSaleIds().length; i++) {
            //GoodsSale goodsSale2 = goodsSaleMapper.selectById(goodsSale.getSaleIds()[i]);
            FactoryProduceSaleAll factoryProduceSaleAll = factoryProduceSaleAllService.selectById(goodsSale.getSaleIds()[i]);
            if (lnGongyi != null && factoryProduceSaleAll != null) {
                factoryProduceSaleAll.setGongyiId(factoryProduceSaleAll.getGongyiId());
                factoryProduceSaleAll.setGongyiName(lnGongyi.getName());
                factoryProduceSaleAll.setGongyiCode(lnGongyi.getCode());
                factoryProduceSaleAll.setGongyiFile(lnGongyi.getFile());
                factoryProduceSaleAll.setGongyiPhoto(lnGongyi.getPhoto());
                factoryProduceSaleAll.setGongyiShuoming(lnGongyi.getShuoming());
                factoryProduceSaleAll.setStatus(BusinessConstants.PROD_STATUS_2);//已分配任务
                factoryProduceSaleAll.setIssheding(BusinessConstants.PROD_STATUS_2);//已分配工艺工序
                factoryProduceSaleAllService.update(factoryProduceSaleAll);
            }
            iGoodsSaledoGongxuService.deleteBySaleId(goodsSale.getSaleIds()[i]);
            if (!rows.isEmpty()) {
                for (GoodsSaledoGongxu entity : rows) {
                    GoodsSaledoGongxu goodsSaledoGongxu = new GoodsSaledoGongxu();
                    goodsSaledoGongxu.setSaleId(factoryProduceSaleAll.getId());
                    goodsSaledoGongxu.setGoodsId(factoryProduceSaleAll.getGoodsId());
                    goodsSaledoGongxu.setGongyiId(factoryProduceSaleAll.getGongyiId());
                    goodsSaledoGongxu.setGongyiName(factoryProduceSaleAll.getGongyiName());
                    goodsSaledoGongxu.setGongyiCode(factoryProduceSaleAll.getGongyiCode());
                    goodsSaledoGongxu.setGongxuId(entity.getId());
                    goodsSaledoGongxu.setCode(entity.getCode());
                    goodsSaledoGongxu.setName(entity.getName());
                    goodsSaledoGongxu.setGongxuName(entity.getGoodsName());
                    goodsSaledoGongxu.setGongxuModel(entity.getGoodsModel());
                    goodsSaledoGongxu.setPhoto(entity.getPhoto());
                    goodsSaledoGongxu.setFile(entity.getFile());
                    goodsSaledoGongxu.setShuoming(entity.getShuoming());
                    goodsSaledoGongxu.setMoney(entity.getMoney());
                    goodsSaledoGongxu.setCounts(factoryProduceSaleAll.getCount());
                    goodsSaledoGongxu.setFenpeiCount(BigDecimal.ZERO);
                    goodsSaledoGongxu.setRemainCount(factoryProduceSaleAll.getCount());
                    goodsSaledoGongxu.setFinishCount(BigDecimal.ZERO);
                    goodsSaledoGongxu.setRemainfinishCount(factoryProduceSaleAll.getCount());
                    goodsSaledoGongxu.setDeptId(entity.getDeptId());
                    goodsSaledoGongxu.setDeptName(entity.getDeptName());
                    goodsSaledoGongxu.setWorkHour(entity.getWorkHour());
                    iGoodsSaledoGongxuService.insert(goodsSaledoGongxu);
                }
            }
        }
    }

    /**
     * 修改销售信息管理
     * @param entity 销售信息管理
     * @return 结果
     */
    @Override
    public int update(GoodsSale entity) {
        entity.setUpdateBy(SecurityUtils.getUsername());
        entity.setUpdateTime(DateUtils.getNowDate());
        BigDecimal fahuoCount = yifahuomingxiService.selectFahuoCountBuySaleId(entity.getId());
        if(fahuoCount == null){
            fahuoCount = BigDecimal.ZERO;
        }
        if(entity.getOrderCount()!=null){
            entity.setFahuoShengyu(entity.getOrderCount().subtract(fahuoCount));
        }
        return goodsSaleMapper.update(entity);
    }

    @Override
    public int editRemark(GoodsSale entity) {
        entity.setUpdateBy(SecurityUtils.getUsername());
        entity.setUpdateTime(DateUtils.getNowDate());
        GoodsSale goodsSale=goodsSaleMapper.selectById(entity.getId());
        entity.setModifyuser(SecurityUtils.getNickName());
        entity.setModifyremark("产品的备注修改了：由"+goodsSale.getRemark()+"；改为："+entity.getRemark());
        /*GoodsSaledo goodsSaledo=new GoodsSaledo();
        goodsSaledo.setGoodsSaleId(entity.getId());*/
        List<GoodsSaledo> goodsSaledoList= saledoService.selectBySaleId(entity.getId());
        if(goodsSaledoList.size()>0){
            for(GoodsSaledo goodsSaledo:goodsSaledoList){
                goodsSaledo.setRemark(entity.getRemark());
                saledoService.update(goodsSaledo);
            }
        }

        return goodsSaleMapper.update(entity);
    }
    @Override
    public int editAgain(GoodsSale entity) {
        entity.setUpdateBy(SecurityUtils.getUsername());
        entity.setUpdateTime(DateUtils.getNowDate());
        entity.setStatus(BusinessConstants.SALE_TYPE_31);
        BigDecimal fahuoCount = yifahuomingxiService.selectFahuoCountBuySaleId(entity.getId());
        if(fahuoCount == null){
            fahuoCount = BigDecimal.ZERO;
        }
        if(entity.getOrderCount()!=null){
            entity.setFahuoShengyu(entity.getOrderCount().subtract(fahuoCount));
        }
        if(StringUtils.isNotBlank(entity.getModifyremark())){
            GoodsSale goodsSale=goodsSaleMapper.selectById(entity.getId());
            if(goodsSale!=null){
                String modifyRemark="";
                for(String remark:entity.getModifyremark().split(",")){
                    if("changeModel".equals(remark)){
                        modifyRemark=modifyRemark+"产品型号由"+goodsSale.getGoodModel()+"更改为："+entity.getGoodModel()+"；";
                    }
                    if("changeCount".equals(remark)){
                        modifyRemark=modifyRemark+"产品数量由"+goodsSale.getOrderCount()+"更改为："+entity.getOrderCount()+"；";
                    }
                    if("changeRemark".equals(remark)){
                        modifyRemark=modifyRemark+"产品备注由"+goodsSale.getRemark()+"更改为："+entity.getRemark()+"；";
                    }
                }
                entity.setModifyuser(SecurityUtils.getNickName());
                entity.setModifyremark(modifyRemark);
            }
        }

        return goodsSaleMapper.update(entity);
    }
    //二次请购
    @Override
    public int addAgain(GoodsSale entity) {
        if (StringUtils.isBlank(entity.getId())) {
            entity.setId(IdUtils.fastSimpleUUID());
        }
        entity.setCreateBy(SecurityUtils.getUsername());
        entity.setCreateTime(DateUtils.getNowDate());
        entity.setFahuoShengyu(entity.getOrderCount());
        entity.setPleaseBuyCount(entity.getOrderCount());
        entity.setStatus(BusinessConstants.SALE_TYPE_0);//产品二次提交
        entity.setModifyuser(SecurityUtils.getNickName());
        entity.setModifyremark("产品二次提交");
        ProjectBaseInfo projectBaseInfo=projectBaseInfoService.selectById(entity.getProjectId());
        if(projectBaseInfo!=null && projectBaseInfo.getContractMoney()!=null){
            projectBaseInfo.setActualMoney(projectBaseInfo.getActualMoney().add(entity.getGoodsTaxTotalPrice()));
        }
        projectBaseInfoService.update(projectBaseInfo);
        return goodsSaleMapper.insert(entity);
    }
    @Override
    public void updateByGongyiId(String id, String gongyiId) {
        goodsSaleMapper.updateByGongyiId(id, gongyiId);
    }

    /**
     * 批量删除销售信息管理
     *
     * @param ids 需要删除的销售信息管理主键
     * @return 结果
     */
    @Override
    public int deleteByIds(String[] ids) {
        return goodsSaleMapper.deleteByIds(ids);
    }

    /**
     * 删除销售信息管理信息
     *
     * @param id 销售信息管理主键
     * @return 结果
     */
    @Override
    public int deleteById(String id) {
        return goodsSaleMapper.deleteById(id);
    }

    @Override
    public int deleteByIdThree(String id) {
        GoodsSale goodsSale=goodsSaleMapper.selectById(id);
        ProjectBaseInfo projectBaseInfo=projectBaseInfoService.selectById(goodsSale.getProjectId());
        projectBaseInfo.setContractMoney(projectBaseInfo.getContractMoney().subtract(goodsSale.getGoodsTaxTotalPrice()));
        projectBaseInfoService.update(projectBaseInfo);
        return goodsSaleMapper.deleteByIdThree(id);
    }

    @Override
    public int deleteByIdFour(String id) {
        return goodsSaleMapper.deleteByIdFour(id);
    }

    @Override
    public void updateFundBackByPrjId(GoodsSale entity) {
        goodsSaleMapper.updateFundBackByPrjId(entity);
    }

    @Override
    public int toAgain(String id) {
        return goodsSaleMapper.toAgain(id);
    }

    @Override
    @Transactional(readOnly = false)
    public int deletSaleInfoForPrj(String id) {
        List<GoodsScalaAll> goodsSaleAllList = iGoodsScalaAllService.selectMainId(id);
        for (GoodsScalaAll goodsScalaAll : goodsSaleAllList) {
            GoodsOrderIn goodsOrderIn = goodsOrderInMapper.selectById(goodsScalaAll.getGoodsId());
            if (goodsOrderIn != null) {
                goodsOrderIn.setRemainderCount(goodsOrderIn.getRemainderCount().add(goodsScalaAll.getGoodsCount()));
                goodsOrderIn.setShengyu(goodsOrderIn.getRemainderCount().multiply(goodsOrderIn.getCostPrice()));
                goodsOrderInMapper.update(goodsOrderIn);

                SysArea sysArea = areaService.selectAreaById(goodsOrderIn.getDeptId());
                sysArea.setShengyu(sysArea.getShengyu().add(goodsOrderIn.getRemainderCount()));
                sysArea.setAllmaoney(sysArea.getAllmaoney().add(goodsOrderIn.getShengyu()));
                areaService.updateArea(sysArea);
            }
            //更新项目费用或者销售金额,利润金额信息
            String projectId = goodsScalaAll.getProjectId();
            ProjectBaseInfo projectBaseInfo = projectBaseInfoService.selectById(projectId);
            if (BusinessConstants.TYPE_PROJECT.equals(goodsScalaAll.getType())) {
                projectBaseInfo.setSaleMoney(projectBaseInfo.getSaleMoney().subtract(goodsScalaAll.getGoodsTotalPrice()));
                projectBaseInfo.setBuyMoney(projectBaseInfo.getBuyMoney().subtract(goodsScalaAll.getGoodsBuyTotal()));
            } else if (BusinessConstants.TYPE_PROJECT_FEE.equals(goodsScalaAll.getType())) {
                projectBaseInfo.setFeeMoney(projectBaseInfo.getFeeMoney().subtract(goodsScalaAll.getGoodsTotalPrice()));
            }
            projectBaseInfo.setProfitMoney(projectBaseInfo.getProfitMoney().add(goodsScalaAll.getGoodsBuyTotal()));
            projectBaseInfoService.update(projectBaseInfo);
        }
        return deleteById(id);
    }

    @Override
    public int updateStatusByPro(String projectId, String status) {
        return goodsSaleMapper.updateStatusByPro(projectId, status);
    }

    @Override
    public Map<String, Object> importData(GoodsSale goodsSale, MultipartFile file,ProjectBaseInfo projectBaseInfo) {
        String tmplName = "goodsSale.xml";
        String errortext = "";
        Map<String, Object> map = new HashMap<>();
        int i = 0;
        int j = 0;
        try {
            InputStream in = new FileInputStream(basePath + File.separator
                    + templatePath + File.separator + templateImport + File.separator + tmplName);
            XLSReader mainReader = ReaderBuilder.buildFromXML(in);
            List<GoodsSale> list = new ArrayList<>();
            List<GoodsSale> listToDo = new ArrayList<>();
            Map beans = new HashMap();
            beans.put("list", list);
            XLSReadStatus readStatus = mainReader.read(file.getInputStream(), beans);
            if (readStatus.isStatusOK()) {
                for (int k = 0; k < list.size(); k++) {
                    GoodsSale entity = new GoodsSale();
                    entity.setId(IdUtils.fastSimpleUUID());
                    GoodsSale info = list.get(k);
                    BeanUtils.copyProperties(info, entity, "id");

                    try {
                        if (StringUtils.isNotBlank(info.getIdx())){
                            entity.setSort(Integer.parseInt(info.getIdx()));
                        }
                    } catch (Exception e) {
                        errortext += "序号为" + info.getIdx() + "行数据，序号应为数字，请修改后导入！";
                        break;
                    }

                    if (StringUtils.isBlank(info.getProjectNo())) {
                        errortext += "序号为" + info.getIdx() + "行数据，订单编号不能为空，请填写后导入！";
                    } else {
                        String projectNo = info.getProjectNo().replace("\n", "").replace("\r", "");
                        if(!projectBaseInfo.getCode().equals(projectNo)){
                            errortext += "序号为" + info.getIdx() + "行数据，订单编号与导入的订单编号不一致，请修改后导入！";
                        }
                        info.setProjectNo(projectNo);
                        ProjectBaseInfo order = projectBaseInfoService.selectByCode(info.getProjectNo());
                        if (order == null) {
                            errortext += "序号为" + info.getIdx() + "行数据，订单编号不存在，请先录入订单！";
                        } else {
                            entity.setProjectId(order.getId());
                            entity.setProjectName(order.getName());
                            entity.setProjectNo(order.getCode());
                        }
                    }
                    try {
                        if(StringUtils.isNotBlank(info.getOrderCountStr())){
                            String orderCountStr = info.getOrderCountStr().replace("\n", "").replace("\r", "");
                            info.setOrderCountStr(orderCountStr);
                            entity.setOrderCount(new BigDecimal(info.getOrderCountStr()));
                        }
                    } catch (Exception e) {
                        errortext += "行号为 " + info.getIdx() + "行的数据，产品数量格式错误，请修改后再上传！";
                        break;
                    }
                    if (StringUtils.isBlank(info.getGoodsCode())) {
                        errortext += "序号为" + info.getIdx() + "行数据，存货编码是空数据，请修改后重新导入！";
                    } else {
                        String goodsCode = info.getGoodsCode().replace("\n", "").replace("\r", "");
                        info.setGoodsCode(goodsCode);
                        GoodsOrderIn goods = goodsOrderInMapper.selectByCode(info.getGoodsCode());
                        if (goods != null) {
                            entity.setGoodsId(goods.getId());
                            entity.setGoodsCode(goods.getCode());
                            entity.setGoodsName(goods.getName());
                            entity.setGoodModel(goods.getModel());
                            entity.setGoodsType(goods.getGoodsType());
                        } else {
                            errortext += "序号为" + info.getIdx() + "行数据，存货编码为:"+info.getGoodsCode()+"，不存在库存内，请检查后导入！";
                        }
                    }
                    try {
                        if(StringUtils.isNotBlank(info.getDeliveryTimeStr())){
                            boolean arriveTimeMatch = Pattern.matches("[0-9]+[.]{0,1}[0-9]*[dD]{0,1}", info.getDeliveryTimeStr());
                            if (!arriveTimeMatch) {
                                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                                entity.setDeliveryTime(df.parse(info.getDeliveryTimeStr()));
                            } else {
                                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                                String date = df.format(DateUtil.getJavaDate(Double.parseDouble(info.getDeliveryTimeStr())));
                                entity.setDeliveryTime(DateUtils.parseDate(date, "yyyy-MM-dd"));
                            }
                        }
                    } catch (Exception e) {
                        errortext += "行号为 " + info.getIdx() + "行的数据，合同到货日期时间格式错误，请修改后再上传！";
                        break;
                    }

                    try {
                        if(StringUtils.isNotBlank(info.getGoodsTaxUnitPriceStr())){
                            entity.setGoodsTaxUnitPrice(new BigDecimal(info.getGoodsTaxUnitPriceStr()));
                            entity.setGoodsUnitPrice(new BigDecimal(info.getGoodsTaxUnitPriceStr()).divide(new BigDecimal("1.13"),3, BigDecimal.ROUND_HALF_UP));
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        errortext += "行号为 " + info.getIdx() + "行的数据，含税单价格式错误，请修改后再上传！";
                        break;
                    }
                    try {
                        if(StringUtils.isNotBlank(info.getGoodsTaxTotalPriceStr())){
                            entity.setGoodsTaxTotalPrice(new BigDecimal(info.getGoodsTaxTotalPriceStr()));
                            entity.setGoodsTotalPrice(new BigDecimal(info.getGoodsTaxTotalPriceStr()).divide(new BigDecimal("1.13"), 3, BigDecimal.ROUND_HALF_UP));
                        }
                    } catch (Exception e) {
                        errortext += "行号为 " + info.getIdx() + "行的数据，含税价格格式错误，请修改后再上传！";
                        break;
                    }
                    if (StringUtils.isNotBlank(errortext)) {
                        map.put("errorText", errortext);
                        map.put("num", i);
                        map.put("numupdate", j);
                        return map;
                    } else {
                        listToDo.add(entity);
                    }
                }
            }
            if (StringUtils.isBlank(errortext)) {
                for (GoodsSale info : listToDo) {
                    i += this.insert(info);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("errorText", errortext);
        map.put("num", i);
        map.put("numupdate", j);
        return map;
    }

    @Override
    public void exportData(HttpServletRequest request, HttpServletResponse response, GoodsSale entity) {
        startPage();
        List<GoodsSale> list = goodsSaleMapper.selectList(entity);
        for (GoodsSale goodsSale : list) {
            ProjectBaseInfo order = goodsSale.getOrder();
            Map<String, Object> params = new HashMap<>();
            order.setGoodsType(DictUtils.getDictLabel("order_goods_type", order.getGoodsType()));
            order.setArea(DictUtils.getDictLabel("order_area", order.getArea()));
            params.put("contractDate", DateUtils.formatDate(order.getContractDate(), "yyyy-MM-dd"));
            params.put("deliveryTime", DateUtils.formatDate(order.getDeliveryTime(), "yyyy-MM-dd"));
            params.put("orderDate", DateUtils.formatDate(order.getOrderDate(), "yyyy-MM-dd"));
            goodsSale.setParams(params);
            goodsSale.setOrder(order);
            params.put("jiaohuoqi", DateUtils.formatDate(goodsSale.getDeliveryTime(), "yyyy-MM-dd"));
            params.put("goodsSaleStatus",DictUtils.getDictLabel("goods_status", goodsSale.getStatus()));
        }

        String fileName = "订单产品列表.xlsx";
        String templateName = "订单产品导出模板.xlsx";
        Map<String, Object> params = new HashMap<>();
        params.put("list", list);
        exportService.baseXlsxExport(fileName, params, templateName, request, response);
    }

    @Override
    public List<GoodsSale> listByOrderIds(GoodsSale entity) {
        return goodsSaleMapper.listByOrderIds(entity);
    }

    @Override
    public List<GoodsSale> listMergeByOrders(GoodsSale entity) {
        return goodsSaleMapper.listMergeByOrders(entity);
    }

    @Override
    public List<GoodsSale> listNoMergeByOrders(GoodsSale entity) {
        return goodsSaleMapper.listNoMergeByOrders(entity);
    }

    @Override
    public List<GoodsSale> selectListYifahuo  (String projectId,String status){
        return goodsSaleMapper.selectListYifahuo(projectId,status);
    }

    @Override
    public void exportMergeDataByOrders(HttpServletRequest request, HttpServletResponse response, GoodsSale entity) {
        List<GoodsSale> list = goodsSaleMapper.listMergeByOrders(entity);

        String orderIds = "";
        StringBuilder orderCodes = new StringBuilder();
        if(entity.getParams()!=null && entity.getParams().get("orderIds")!=null){
            orderIds = entity.getParams().get("orderIds").toString();
        }

        ProjectBaseInfo projectBaseInfo = new ProjectBaseInfo();
        Map<String, Object> param = new HashMap<>();
        param.put("orderIds", orderIds);
        projectBaseInfo.setParams(param);
        List<ProjectBaseInfo> orders =  projectBaseInfoService.selectList(projectBaseInfo);
        for (ProjectBaseInfo order : orders) {
            orderCodes.append(order.getCode()).append(",");
        }

        String fileName = "多订单产品订单产品列表.xlsx";
        String templateName = "多订单产品合并导出模板.xlsx";
        Map<String, Object> params = new HashMap<>();
        params.put("list", list);
        params.put("orderCodes", orderCodes.toString());
        exportService.baseXlsxExport(fileName, params, templateName, request, response);
    }


    @Override
    public void updateStatusById  (String id,String status){
        goodsSaleMapper.updateStatusById(id,status);
    }

    /**
     * 根据订单 导出 不合并产品明细表
     *
     * @param entity 销售信息管理
     * @return 结果
     */
    @Override
    public void exportNoMergeDataByOrders(HttpServletRequest request, HttpServletResponse response, GoodsSale entity) {
        List<GoodsSale> list = goodsSaleMapper.listNoMergeByOrders(entity);

        // 翻译字典 和 日期
        for (GoodsSale goodsSale : list) {
            ProjectBaseInfo order = goodsSale.getOrder();
            Map<String, Object> params = new HashMap<>();
            order.setGoodsType(DictUtils.getDictLabel("order_goods_type", order.getGoodsType()));
            order.setArea(DictUtils.getDictLabel("order_area", order.getArea()));
            params.put("contractDate", DateUtils.formatDate(order.getContractDate(), "yyyy-MM-dd"));
            params.put("deliveryTime", DateUtils.formatDate(order.getDeliveryTime(), "yyyy-MM-dd"));
            params.put("orderDate", DateUtils.formatDate(order.getOrderDate(), "yyyy-MM-dd"));
            goodsSale.setParams(params);
        }


        String fileName = "多订单产品订单产品列表（不合并产品）.xlsx";
        String templateName = "多订单不合并产品导出模板.xlsx";
        Map<String, Object> params = new HashMap<>();
        params.put("list", list);
        exportService.baseXlsxExport(fileName, params, templateName, request, response);
    }





}
